package org.windblog.core;

import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.windblog.core.entity.Comment;
import org.windblog.core.entity.Post;
import org.windblog.core.filter.PersistenceFilter;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class CommentService {

	private static PersistenceManager pm = null;
	
	public static void setComment(Comment comment)
	{
		pm = PersistenceFilter.getManager();
		pm.makePersistent(comment);
	}
	
	public static Comment getComment(Key key)
	{
		if (key == null)
			return null;
		pm = PersistenceFilter.getManager();
		try {
			Comment comment = pm.getObjectById(Comment.class, key);
			return comment;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	public static Comment getComment(String strkey)
	{
		Key key = KeyFactory.stringToKey(strkey);
		return getComment(key);
	}

	
	public static void deleteComment(Comment comment) {
		deleteCommentFromPost(comment.getPost(), comment);
		pm = PersistenceFilter.getManager();
		pm.deletePersistent(comment);
	}
	

	@SuppressWarnings("unchecked")
	public static List<Comment> getComments(String filter)
	{
		List<Comment> comts = new LinkedList<Comment>();
		pm = PersistenceFilter.getManager();
		Query query = null;
		if (filter.trim().equals(""))
		{
			query = pm.newQuery(Comment.class);
		}else
		{
			query = pm.newQuery(Comment.class, filter);
		}
		comts = (List<Comment>) query.execute();
		query.closeAll();
		return comts;
	}
	
	public static List<Comment> getAllComments()
	{
		return getComments("type != 'SPAM' ");
	}
	
	public static List<Comment> getApprovedComments()
	{
		return getComments("type == 'APPROVED' ");
	}
	
	public static List<Comment> getPendingComments()
	{
		return getComments("type == 'PENDING'");
	}
	
	public static List<Comment> getSpamComments()
	{
		return getComments("type == 'SPAM'");
	}
	public static void addCommentToPost(Post post ,Comment com)
	{
		Key postKey = post.getKey();
		Key comKey = com.getKey();
		if(postKey==null || comKey ==null)
			throw new NullPointerException("cat or post's key is null.please ensure these object have been persistenced.");
		com.setPostKey(postKey);
		post.addCommentKey(comKey);
	}
	
	public static void deleteCommentFromPost(Post post , Comment com)
	{
		Key postKey = post.getKey();
		Key comKey = com.getKey();
		if(postKey==null || comKey ==null)
			throw new NullPointerException("cat or post's key is null.please ensure these object have been persistenced.");
		com.setPostKey(null);
		post.deleteCommentKey(comKey);
	}
	
	

}
